package com.gdhz.xiaohengqin.handler;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gdhz.xiaohengqin.device.constants.WieGandConstant;
import com.gdhz.xiaohengqin.device.model.entity.AccessRecord;
import com.gdhz.xiaohengqin.device.service.AccessRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author Swallows
 * @date 2025-05-30 16:03
 */
@Slf4j
@Component
public class AccessRecordHandler implements MessageHandler {

    private final ObjectMapper mapper;
    private final AccessRecordService accessRecordService;

    public AccessRecordHandler(ObjectMapper mapper, AccessRecordService accessRecordService) {
        this.mapper = mapper;
        this.accessRecordService = accessRecordService;
    }

    @Override
    public boolean canHandle(JsonNode message) {
        return message.get(0).has(WieGandConstant.MESSAGE_TYPE_RECORD);
    }

    @Override
    public Mono<Void> handle(JsonNode message) {
        log.info("开门记录信息进来了");
        return Flux.fromIterable(message::elements)
                .flatMap(element -> {
                    AccessRecord record = mapper.convertValue(element,  AccessRecord.class);
                    return accessRecordService.saveRecord(record);  // 直接整合保存操作
                })
                .onErrorResume(e -> {
                    log.error(" 处理开门数据失败: {}", message, e);
                    return Mono.empty();
                })
                .then();
    }
}
